<script setup lang="ts">
import { doGetShopBalance, doPostWithdraw } from '@/apis/finance'
import { ElMessage } from 'element-plus'
import { QuestionFilled } from '@element-plus/icons-vue'
import { doPostExportShopWithdrawData } from '@/apis/overview'
import PageManage from '@/components/PageManage.vue'
import SchemaForm from '@/components/SchemaForm.vue'
import { doGetWithdrawList } from '@/apis/finance'

interface SearchParams {
    status: string
    startDate: string
    endDate: string
    no: string
    supplier: string
}

const showDescriptionDialog = ref(false)
const balanceInfo = reactive({
    withdrawing: '0',
    withdrawalTotal: '0',
    undrawn: '0',
})
const tabPaneName = ref('APPLYING')
const { divTenThousand } = useConvert()
const showWithdrawDialog = ref(false)
const pageConfig = reactive({
    size: 10,
    current: 1,
    total: 0,
})
const searchParams = reactive({
    status: 'APPLYING',
    startDate: '',
    endDate: '',
    no: '',
    supplier: '',
    date: [],
})
const columns = [
    {
        label: '交易流水号',
        labelWidth: 85,
        prop: 'no',
        valueType: 'copy',
        fieldProps: {
            placeholder: '请输入',
        },
    },
    {
        label: '交易时间',
        prop: 'date',
        valueType: 'date-picker',
        fieldProps: {
            type: 'daterange',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间',
            format: 'YYYY/MM/DD',
            valueFormat: 'YYYY-MM-DD',
            onChange: (data: string[] | null) => {
                handleChangeDate(data)
            },
        },
    },
]
const handleChangeDate = (e: string[] | null) => {
    if (e) {
        searchParams.startDate = e[0]
        searchParams.endDate = e[1]
    } else {
        searchParams.startDate = ''
        searchParams.endDate = ''
    }
    initWithdrawList()
}
function convertStatus(val: string) {
    const statusType: { [x: string]: string } = {
        APPLYING: '待审核',
        SUCCESS: '已到账',
        CLOSED: '已拒绝',
        FORBIDDEN: '已拒绝',
    }
    return statusType[val]
}
watch(
    () => tabPaneName.value,
    () => {
        pageConfig.current = 1
        initWithdrawList()
        initBalance()
    },
    { immediate: true },
)

/**
 * 重置表单
 */
const handleReset = () => {
    ;(Object.keys(searchParams) as (keyof SearchParams)[]).forEach((key) => (searchParams[key] = ''))
    initWithdrawList()
}
const handleShowDialog = () => {
    showWithdrawDialog.value = true
}
const withdrawValue = ref(0.01)
async function initBalance() {
    const { code, data, msg } = await doGetShopBalance()
    if (code === 200) {
        balanceInfo.undrawn = data.undrawn
        balanceInfo.withdrawalTotal = data.withdrawalTotal
        balanceInfo.withdrawing = data.withdrawing
    } else {
        ElMessage.error(msg ? msg : '获取余额信息失败')
    }
}
/**
 * 表格排序
 */
let sortEnum = ref('')
const sortTableList = (label: string) => {
    switch (label) {
        case '提现金额(元)':
            sortEnum.value = sortEnum.value === '' ? '' : ''
            initBalance()
            break
        case '申请时间':
            sortEnum.value = sortEnum.value === '' ? '' : ''
            initBalance()
            break
        case '审批时间':
            sortEnum.value = sortEnum.value === '' ? '' : ''
            initBalance()
            break
        default:
            break
    }
}

/**
 * 获取表格数据
 */
initBalance()
const withdrawList = ref([])
async function initWithdrawList() {
    // 商家端 'SHOP'   供应商端  'SUPPLIER'
    const type = 'SHOP'
    const { code, data, msg } = await doGetWithdrawList({ ...pageConfig, ...searchParams, status: tabPaneName.value, type })
    if (code === 200) {
        withdrawList.value = data.records
        pageConfig.total = data.total
    } else {
        ElMessage.error(msg ? msg : '获取提现列表失败')
    }
}

const checkedData = ref<any[]>([]) // 选中数据

// 处理选择变化
function handleSelectionChange(selection: any[]) {
    checkedData.value = selection
}
const handleExport = async () => {
    const params: any = {}
    if (checkedData.value.length) {
        params.exportIds = checkedData.value.map((item) => item.id)
    }
    const { code, msg } = await doPostExportShopWithdrawData(params)
    if (code === 200) {
        ElMessage.success({ message: msg || '导出成功' })
    } else {
        ElMessage.error({ message: msg || '导出失败' })
    }
}

// 商家端 'SHOP'，供应商 'SUPPLIER'
const type = 'SHOP'
const handleSubmit = async () => {
    try {
        if (withdrawValue.value < 0.01) {
            return ElMessage.error('输入值最小为0.01')
        }
        if (withdrawValue.value > Number(divTenThousand(balanceInfo.undrawn))) {
            return ElMessage.error('提现金额不可大于店铺余额')
        }
        const { code, msg } = await doPostWithdraw(withdrawValue.value * 10000, type)
        if (code === 200) {
            ElMessage.success('申请成功')
            showWithdrawDialog.value = false
            initBalance()
            initWithdrawList()
        } else {
            ElMessage.error(msg ? msg : '申请失败')
        }
    } catch (error) {
        ElMessage.error('申请失败')
    }
}
const handleCloseDialog = () => {
    withdrawValue.value = 0.01
}
const handleChangeCurrent = (e: number) => {
    pageConfig.current = e
    initWithdrawList()
}
const handleChangeSize = (e: number) => {
    pageConfig.current = 1
    pageConfig.size = e
    initWithdrawList()
}
</script>

<template>
    <SchemaForm v-model="searchParams" :columns="columns" @searchHandle="initWithdrawList" @handleReset="handleReset" />
    <div class="grey_bar"></div>
    <div class="settle">
        <div class="settle__item">
            <div>
                <div class="settle__item--title" style="display: flex; align-items: center">
                    <span>店铺余额</span>
                    <el-icon class="export-icon" style="font-size: 16px; margin-left: 5px; cursor: pointer" @click="showDescriptionDialog = true"
                        ><QuestionFilled
                    /></el-icon>
                </div>
                <div class="settle__item--price">{{ divTenThousand(balanceInfo.undrawn) }}</div>
                <div>
                    <el-button type="primary" @click="handleShowDialog">提现</el-button>
                </div>
            </div>
            <img src="@/assets/images/storeBalance.png" />
        </div>
        <div class="settle__item">
            <div>
                <div class="settle__item--title">累计提现</div>
                <div class="settle__item-bottom">
                    <div class="settle__item--price">{{ divTenThousand(balanceInfo.withdrawalTotal) }}</div>
                </div>
            </div>
            <img src="@/assets/images/accumulatedWithdrawal.png" />
        </div>
        <div class="settle__item">
            <div>
                <div class="settle__item--title">提现中</div>
                <div class="settle__item-bottom">
                    <div class="settle__item--price">{{ divTenThousand(balanceInfo.withdrawing) }}</div>
                </div>
            </div>
            <img src="@/assets/images/withdrawalIn.png" />
        </div>
    </div>
    <div class="tab_container">
        <el-tabs v-model="tabPaneName">
            <el-tab-pane label="待审核" name="APPLYING" />
            <el-tab-pane label="已到账" name="SUCCESS" />
            <el-tab-pane label="已拒绝" name="FORBIDDEN" />
            <!-- <purchase-expenditure /> -->
        </el-tabs>
    </div>
    <div class="handle_container">
        <el-button size="small" type="primary" @click="handleExport">导出</el-button>
    </div>
    <template v-if="tabPaneName !== 'purchase'">
        <!-- <basic-settle ref="basicSetterRef" v-model:checked-data="checkedData" :status="tabPaneName" /> -->
        <div class="table_container">
            <el-table
                :data="withdrawList"
                style="width: 100%"
                :header-cell-style="{
                    backgroundColor: '#F6F8FA',
                    color: '#333',
                    height: '48px',
                }"
                :cell-style="{ color: '#333', height: '60px' }"
                @selection-change="handleSelectionChange"
            >
                <template #empty> <ElTableEmpty /> </template>
                <!-- @selection-change="handleChangeSelection" -->
                <el-table-column type="selection" fixed="left" />
                <el-table-column label="交易流水号" prop="no"></el-table-column>
                <el-table-column label="申请时间" prop="createTime">
                    <template #header>
                        <span>申请时间</span>
                        <!-- <i style="font-size: 12px; margin-left: 5px" class="iconfont icon-path" @click="sortTableList('申请时间')"></i> -->
                    </template>
                </el-table-column>
                <el-table-column v-if="tabPaneName === 'SUCCESS' || tabPaneName === 'FORBIDDEN'" label="审批时间" prop="tradeTime">
                    <template #header>
                        <span>审批时间</span>
                        <!-- <i style="font-size: 12px; margin-left: 5px" class="iconfont icon-path" @click="sortTableList('审批时间')"></i> -->
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="200">
                    <template #default="{ row }">
                        <div>{{ convertStatus(row.status) }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="提现金额(元)" width="200">
                    <template #header>
                        <span>提现金额(元)</span>
                        <!-- <i style="font-size: 12px; margin-left: 5px" class="iconfont icon-path" @click="sortTableList('提现金额(元)')"></i> -->
                    </template>
                    <template #default="{ row }">
                        <div>{{ divTenThousand(row.drawType.amount) }}</div>
                    </template>
                </el-table-column>
                <el-table-column v-if="tabPaneName === 'FORBIDDEN'" label="拒绝说明" prop="reason" align="right">
                    <template #default="{ row }">
                        <el-tooltip class="box-item" effect="dark" placement="bottom">
                            <template #content>
                                <div style="max-width: 447px">{{ row.reason }}</div>
                            </template>
                            <span style="color: #555cfd">拒绝说明</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <pageManage
            :page-num="pageConfig.current"
            :page-size="pageConfig.size"
            :total="pageConfig.total"
            @handle-current-change="handleChangeCurrent"
            @handle-size-change="handleChangeSize"
        />
    </template>
    <el-dialog v-model="showWithdrawDialog" title="提现申请" center width="320px" top="25vh" @close="handleCloseDialog">
        <el-form>
            <el-form-item label="提现金额" required>
                <el-input-number v-model="withdrawValue" :min="0.01" :precision="2" :controls="false" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="showWithdrawDialog = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
        </template>
    </el-dialog>
    <el-dialog v-model="showDescriptionDialog" :width="650" title="店铺余额说明">
        <p class="dialog-line">
            1、店铺余额是指店铺卖出商品（订单状态已完成计入）获得的经营收入，店铺可向平台发起提现即将资金由平台处转到店铺账户上以此实现店铺与平台之间的资金(分账)结算。
        </p>
        <p class="dialog-line">2、累计提现是指该商家所有提现成功的金额之和</p>
        <p class="dialog-line">3、提现中是指待审批提现工单中的提现金额之和，提现失败提现金额还给供应商余额，提现成功提现金额计入累计提现中</p>
        <p class="dialog-line">4、店铺采购商品如使用线上支付(店铺余额)，则店铺余额会减小相应金额，具体明细可查看对账单和采购订单。</p>
    </el-dialog>
</template>

<style lang="scss" scoped>
@include b(settle) {
    color: #000;
    @include flex(space-between);
    padding: 16px;
    @include e(item) {
        width: 390px;
        height: 132px;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        padding: 20px 30px 15px 30px;
        border-radius: 6px;
        border: 2px solid #e9ecf0;
        img {
            width: 65px;
            height: 55px;
            position: relative;
            top: 22px;
        }
        @include m(title) {
            font-size: 14px;
            color: #999;
        }
        @include m(price) {
            font-size: 24px;
            font-weight: 400;
            margin: 8px 0;
            &::before {
                content: '￥';
                display: inline-block;
                font-size: 13px;
                vertical-align: baseline;
            }
        }
        &:nth-child(n) {
            background-size: 100% 100%;
            background-repeat: no-repeat;
        }
    }
    @include e(item-bottom) {
        @include flex(space-between, flex-end);
    }
}
@include b(dialog-line) {
    line-height: 2;
}
</style>
